package cn.tedu.egcar1.controller;

import cn.tedu.egcar1.base.response.JsonResult;
import cn.tedu.egcar1.base.response.StatusCode;
import cn.tedu.egcar1.mapper.UserMapper;
import cn.tedu.egcar1.pojo.dto.UserLoginParam;
import cn.tedu.egcar1.pojo.dto.UserRegParam;
import cn.tedu.egcar1.pojo.entity.User;
import cn.tedu.egcar1.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Slf4j
@Tag(name="用户管理模块")
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    @Operation(summary = "注册")
    @ApiOperationSupport(order = 10)
    public JsonResult reg(@RequestBody UserRegParam userRegParam){
        if(userMapper.selectUserByUsername(userRegParam.getUsername())>0){
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        if (userMapper.insertUser(user)>0){
            return JsonResult.ok();
        }else
            return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @PostMapping("login")
    @Operation(summary = "登录")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam){
        UserVO userVO = userMapper.selectUserByUsernameAndPassword(userLoginParam);
        if(userVO!=null){
        return JsonResult.ok();
        }else return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }
}
